{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "# 两种方法\n",
    "import keras\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from keras.utils import np_utils\n",
    "\n",
    "from keras.datasets import mnist\n",
    "# Sequential按顺序构成的模型\n",
    "from keras.models import Sequential\n",
    "# Dense全连接层\n",
    "from keras.layers import Dense,Activation\n",
    "# 优化器\n",
    "from keras.optimizers import SGD\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "xtrain (60000, 28, 28)\n",
      "ytrain (60000,)\n",
      "xtrain (60000, 784)\n",
      "xtest (10000, 784)\n",
      "Epoch 1/10\n",
      "60000/60000 [==============================] - 4s 60us/step - loss: 0.3668 - accuracy: 0.8939\n",
      "Epoch 2/10\n",
      "60000/60000 [==============================] - 3s 49us/step - loss: 0.3038 - accuracy: 0.9137\n",
      "Epoch 3/10\n",
      "60000/60000 [==============================] - 3s 54us/step - loss: 0.2925 - accuracy: 0.9174\n",
      "Epoch 4/10\n",
      "60000/60000 [==============================] - 3s 57us/step - loss: 0.2869 - accuracy: 0.9198\n",
      "Epoch 5/10\n",
      "60000/60000 [==============================] - 4s 60us/step - loss: 0.2811 - accuracy: 0.9215\n",
      "Epoch 6/10\n",
      "60000/60000 [==============================] - 4s 60us/step - loss: 0.2781 - accuracy: 0.9227\n",
      "Epoch 7/10\n",
      "60000/60000 [==============================] - 3s 57us/step - loss: 0.2752 - accuracy: 0.9230\n",
      "Epoch 8/10\n",
      "60000/60000 [==============================] - 4s 64us/step - loss: 0.2745 - accuracy: 0.9232\n",
      "Epoch 9/10\n",
      "60000/60000 [==============================] - 3s 54us/step - loss: 0.2719 - accuracy: 0.9236\n",
      "Epoch 10/10\n",
      "60000/60000 [==============================] - 3s 51us/step - loss: 0.2705 - accuracy: 0.9246\n",
      "10000/10000 [==============================] - 0s 34us/step\n",
      "\test loss 0.28386929122805593\n",
      "accuray 0.919700026512146\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# 载入数据\n",
    "(x_train,y_train),(x_test,y_test)=mnist.load_data()\n",
    "\n",
    "print('xtrain',x_train.shape)\n",
    "print('ytrain',y_train.shape)\n",
    "\n",
    "# -1是自动转换，255.0是为了归一化\n",
    "x_train=x_train.reshape(x_train.shape[0],-1)/255.0\n",
    "x_test=x_test.reshape(x_test.shape[0],-1)/255.0\n",
    "\n",
    "print('xtrain',x_train.shape)\n",
    "print('xtest',x_test.shape)\n",
    "\n",
    "# 转化成one-hot格式\n",
    "y_train=np_utils.to_categorical(y_train,num_classes=10)\n",
    "y_test=np_utils.to_categorical(y_test,num_classes=10)\n",
    "\n",
    "# 创建模型,输入784个神经元，输出10个神经元\n",
    "model=Sequential(\n",
    "[Dense(units=10,input_dim=784,bias_initializer='one',activation='softmax')]\n",
    ")\n",
    "\n",
    "\n",
    "# 分类模型使用交叉熵速度比较快\n",
    "sgd=SGD(lr=0.3)\n",
    "model.compile(optimizer=sgd,loss='categorical_crossentropy',metrics=['accuracy'])\n",
    "\n",
    "# 训练\n",
    "# batch_size=32一次训练32章，epochs 训练10轮，把所有的图片都训练一次\n",
    "model.fit(x_train,y_train,batch_size=32,epochs=10)\n",
    "#评估模型\n",
    "loss,accuray=model.evaluate(x_test,y_test)\n",
    "\n",
    "print('\\test loss',loss)\n",
    "print('accuray',accuray)\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 保存模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# HDF5 文件\n",
    "model.save('model.h5')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.models import load_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model=load_model('model.h5')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/20\n",
      "60000/60000 [==============================] - 2s 37us/step - loss: 0.2547 - accuracy: 0.9302\n",
      "Epoch 2/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2530 - accuracy: 0.9303\n",
      "Epoch 3/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2536 - accuracy: 0.9291\n",
      "Epoch 4/20\n",
      "60000/60000 [==============================] - 2s 32us/step - loss: 0.2524 - accuracy: 0.9297\n",
      "Epoch 5/20\n",
      "60000/60000 [==============================] - 2s 29us/step - loss: 0.2519 - accuracy: 0.9303\n",
      "Epoch 6/20\n",
      "60000/60000 [==============================] - 2s 29us/step - loss: 0.2518 - accuracy: 0.9305\n",
      "Epoch 7/20\n",
      "60000/60000 [==============================] - 2s 34us/step - loss: 0.2511 - accuracy: 0.9299\n",
      "Epoch 8/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2502 - accuracy: 0.9308\n",
      "Epoch 9/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2500 - accuracy: 0.9313\n",
      "Epoch 10/20\n",
      "60000/60000 [==============================] - 2s 34us/step - loss: 0.2500 - accuracy: 0.9306\n",
      "Epoch 11/20\n",
      "60000/60000 [==============================] - 2s 31us/step - loss: 0.2499 - accuracy: 0.9302\n",
      "Epoch 12/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2487 - accuracy: 0.9313\n",
      "Epoch 13/20\n",
      "60000/60000 [==============================] - 2s 34us/step - loss: 0.2481 - accuracy: 0.9313\n",
      "Epoch 14/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2480 - accuracy: 0.9318\n",
      "Epoch 15/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2475 - accuracy: 0.9311\n",
      "Epoch 16/20\n",
      "60000/60000 [==============================] - 2s 34us/step - loss: 0.2474 - accuracy: 0.9310\n",
      "Epoch 17/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2469 - accuracy: 0.9311\n",
      "Epoch 18/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2466 - accuracy: 0.9316\n",
      "Epoch 19/20\n",
      "60000/60000 [==============================] - 2s 34us/step - loss: 0.2469 - accuracy: 0.9306\n",
      "Epoch 20/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.2452 - accuracy: 0.9315\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.callbacks.History at 0x266f4b83a20>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.fit(x_train,y_train,batch_size=64,epochs=20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 保存参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model.save_weights('my_weight.h5')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model.load_weights('my_weight.h5')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 保存结构"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from keras.models import model_from_json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "json_to_string=model.to_json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"class_name\": \"Sequential\", \"config\": {\"name\": \"sequential_1\", \"layers\": [{\"class_name\": \"Dense\", \"config\": {\"name\": \"dense_1\", \"trainable\": true, \"batch_input_shape\": [null, 784], \"dtype\": \"float32\", \"units\": 10, \"activation\": \"softmax\", \"use_bias\": true, \"kernel_initializer\": {\"class_name\": \"VarianceScaling\", \"config\": {\"scale\": 1.0, \"mode\": \"fan_avg\", \"distribution\": \"uniform\", \"seed\": null}}, \"bias_initializer\": {\"class_name\": \"Ones\", \"config\": {}}, \"kernel_regularizer\": null, \"bias_regularizer\": null, \"activity_regularizer\": null, \"kernel_constraint\": null, \"bias_constraint\": null}}]}, \"keras_version\": \"2.3.1\", \"backend\": \"tensorflow\"}\n"
     ]
    }
   ],
   "source": [
    "print(json_to_string)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model1=model_from_json(json_to_string)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<keras.engine.sequential.Sequential object at 0x00000266F5ABB828>\n"
     ]
    }
   ],
   "source": [
    "print(model1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
